package pay.utils;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageInputStream;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.io.*;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.util.Iterator;

/**
 * 文件加密相关
 */
public class PicUtil {

    private static Logger logger = LoggerFactory.getLogger(PicUtil.class);

    private static final  String tempFileAddress = "/pics";
    private static File tempFolder = new File(tempFileAddress);


    {
        if (!tempFolder.exists()) {
            tempFolder.mkdir();
        }
    }

    /**
     * 创建临时文件
     * @param file
     * @param picId
     */
    public static void  createTempFile(MultipartFile file, String picId){
        BufferedOutputStream out = null;//保存图片到目录下
        try {
            out = new BufferedOutputStream(
                    new FileOutputStream( File.createTempFile(picId, ".jpg", tempFolder )));
            out.write(file.getBytes());
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("保存临时文件错误 e={}", e);
        }

    }


    /**
     * 根据picId, 获取图片全名
     * @param picId
     * @return
     */
    public static String getTempFileName(String picId){
        String filename = "";
        File[] tempList = tempFolder.listFiles();
        logger.info("该目录下对象个数 ={}", tempList.length);
        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile() && tempList[i].toString().indexOf(picId) >= 0){
                filename = tempList[i].toString();
            }
        }

        return  filename;
    }

    /**
     * 根据picId, 检测图片是否已上传
     * @param picId
     * @return
     */
    public static  Boolean checkFileExist(String picId){
        String filename = null;
        File[] tempList = tempFolder.listFiles();
        if(tempList == null || tempList.length == 0){
            logger.info("this file in the tempList is null");
            return  false;
        }
        logger.info("该目录下对象个数={}", tempList.length);
        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile() && tempList[i].toString().indexOf(picId) >= 0){
                filename = tempList[i].toString();
            }
        }

        return  filename != null?true:false ;
    }


    /**
     * 根据picId, 获取图片
     * @param picId
     * @return
     */
    public static  File getPicById(String picId){
        if(!checkFileExist(picId)){
            return  null;
        }

        String filename = getTempFileName(picId);

        return new File(filename);
    }

    /**
     * @Title: compressPicByQuality
     * @Description: 压缩图片,通过压缩图片质量，保持原图大小
     * @param  quality：0-1
     * @return byte[]
     * @throws
     */
    public static byte[] compressPicByQuality(byte[] imgByte, float quality) {
        byte[] inByte = null;
        try {
            ByteArrayInputStream byteInput = new ByteArrayInputStream(imgByte);
            BufferedImage image = ImageIO.read(byteInput);

            // 如果图片空，返回空
            if (image == null) {
                return null;
            }

            // 得到指定Format图片的writer
            Iterator<ImageWriter> iter = ImageIO
                    .getImageWritersByFormatName("jpeg");// 得到迭代器
            ImageWriter writer = (ImageWriter) iter.next(); // 得到writer

            // 得到指定writer的输出参数设置(ImageWriteParam )
            ImageWriteParam iwp = writer.getDefaultWriteParam();
            iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); // 设置可否压缩
            iwp.setCompressionQuality(quality); // 设置压缩质量参数

            iwp.setProgressiveMode(ImageWriteParam.MODE_DISABLED);

            ColorModel colorModel = ColorModel.getRGBdefault();
            // 指定压缩时使用的色彩模式
            iwp.setDestinationType(new javax.imageio.ImageTypeSpecifier(colorModel,
                    colorModel.createCompatibleSampleModel(16, 16)));

            // 开始打包图片，写入byte[]
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // 取得内存输出流
            IIOImage iIamge = new IIOImage(image, null, null);

            // 此处因为ImageWriter中用来接收write信息的output要求必须是ImageOutput
            // 通过ImageIo中的静态方法，得到byteArrayOutputStream的ImageOutput
            writer.setOutput(ImageIO
                    .createImageOutputStream(byteArrayOutputStream));
            writer.write(null, iIamge, iwp);
            inByte = byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            System.out.println("write errro");
            e.printStackTrace();
        }
        return inByte;
    }
}
